package com.study.spmongodb.wwj.thread2.char16;

import java.io.*;
import java.net.Socket;

/**
 * @author study
 * @version 1.0
 * @date 2020/12/9 10:33
 */
public class ClientHandler implements Runnable {


    private final Socket socket;

    private volatile boolean running = true;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream();
             BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
             PrintWriter printWriter = new PrintWriter(outputStream)
        ) {
            while (running) {
                String msg = br.readLine();
                if (null == msg) {
                    break;
                }
                System.out.println("come from client msg->" + msg);
                printWriter.write("echo " + msg + "\n");
                printWriter.flush();
            }
        } catch (Exception e) {
            this.running = true;
        } finally {
            System.out.println("client  leave");
            this.stop();
        }


    }

    public void stop() {
        if (running) {
            return;
        }
        System.out.println("client  leave");
        this.running = false;
        try {
            this.socket.close();
        } catch (IOException e) {
            //
        }
    }
}
